﻿using System.Text.Json.Serialization;
namespace System.Text.Json
{
    /// <summary>
    ///Startup json时间格式化转换解析器
    /// 使用方法  services.AddControllers().AddJsonOptions(options => {
    //           options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    //         options.JsonSerializerOptions.Converters.Add(new DatetimeFormatJsonConverter("yyyy-MM-dd HH:mm:ss"));
    //     });
    /// </summary>
    public class DatetimeobjFormatJsonConverter:JsonConverter<DateTime?>
    {
        private readonly string Format = "yyyy-MM-dd HH:mm:ss";
        public DatetimeobjFormatJsonConverter(string format= "yyyy-MM-dd HH:mm:ss")
        {
            Format = format;
        }

        public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            try
            {
                return DateTime.ParseExact(reader.GetString(), Format, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine("read=" + ex.Message);
                return null;
            }
        }

        public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
        {
            try
            {
                writer.WriteStringValue(((DateTime)value).ToString(Format));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Write=" + ex.Message);
            }
        }
    }


    /// <summary>
    /// json时间格式化转换解析器
    /// 使用方法  services.AddControllers().AddJsonOptions(options => {
    //           options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    //         options.JsonSerializerOptions.Converters.Add(new DatetimeFormatJsonConverter("yyyy-MM-dd HH:mm:ss"));
    //     });
    /// </summary>
    public class DatetimeFormatJsonConverter : JsonConverter<DateTime>
    {
        private readonly string Format= "yyyy-MM-dd HH:mm:ss";
        public DatetimeFormatJsonConverter(string format= "yyyy-MM-dd HH:mm:ss")
        {
            Format = format;
        }

        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
           
                return DateTime.ParseExact(reader.GetString(), Format, null);
          
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            try
            {
                writer.WriteStringValue((value).ToString(Format));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Write=" + ex.Message);
            }
        }
    }
}
